package com.netty.modbus.handler;

import com.netty.modbus.dto.DataReceiveBody;
import com.netty.modbus.util.HexUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;

import java.nio.Buffer;

/**
 * description: DataHandlerExample @ChannelHandler.Sharable单利模式处理器 <br>
 * date: 2021/10/11 15:26 <br>
 * @author: lwy <br>
 * @version: 1.0 <br>
 */
@ChannelHandler.Sharable
public class DataHandlerExample extends InHandler{

    @Override
    protected void alarmSettingData(DataReceiveBody data) {
        //获取设备唯一编号
        data.getDevNumber();
        System.out.println("报警设置数据:"+HexUtil.byte2HexStr(data.getData()));
    }

    @Override
    protected void readAlarmSettingData(DataReceiveBody data) {
        //获取读取寄存器的起始位置
        data.getStartAddress();
        data.getQuantity();
        System.out.println("读取的报警设置数据:"+HexUtil.byte2HexStr(data.getData()));
    }

    @Override
    protected void writeAlarmSettingBackData(DataReceiveBody data) {
        System.out.println("写入数据后反馈:"+HexUtil.byte2HexStr(data.getStartAddress())+","
                +HexUtil.HexStringToInt(HexUtil.byte2HexStr(data.getQuantity())));

    }

    @Override
    protected void realTimeData(DataReceiveBody data) {
        //实时数据中包含了消息体长度两个字节需要去掉
        byte[] dataByte=new byte[data.getData().length-2];
        System.arraycopy(data.getData(),2,dataByte,0,data.getData().length-2);
        System.out.println("实时数据:"+HexUtil.byte2HexStr(dataByte));

        //信号值
        int sign=HexUtil.HexStringToInt(HexUtil.bytesToHex(getPos(17,0,dataByte))) ;
        byte[] wdByte= getPos(34,35,dataByte);
        System.out.println("温度："+HexUtil.bytesToHex(wdByte));
        float wd=HexUtil.getFloat(wdByte);
        System.out.println("信号值："+sign+";温度4："+wd);
    }

    private byte[] getPos(int start,int end,byte[] data){
        //地址计算，一个地址上2个字节的内容
        int startByte=start*2;
        int length;
        if(end!=0){
            length=(end-start)*2+2;
        }else {
            length=2;
        }
        byte[] bytes=new byte[length];
        System.arraycopy(data,startByte,bytes,0,length);
        return bytes;
    }

}
